<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="$t('添加')" append-to-body :v-if="dialogVisible" :visible.sync="dialogVisible" width="570px" top="5%" @close='close'>
    <el-form ref="form" :model="record" :inline="true" label-width="120px" :rules="rules" label-position="left" style="margin:0 25px;">
      <el-form-item :label="$t('寄存器区间')" prop="register_interval">
        <el-select v-model="record.register_interval" class="addTypeForm" ref='interval' size='small' filterable @change="intervalChange">
          <el-option v-for="(value, key) in intervalList" :key="key" :label="value" :value="key"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('db值')" prop="db_num" v-if="showDbNumList.includes(record.register_interval)" :key="key">
        <el-input v-emoji v-model="record.db_num" ref="num" class="addTypeForm" size='small'></el-input>
      </el-form-item>
      <el-form-item :label="$t('寄存器起始地址')" prop="register_address_start" style="margin-right:0">
        <el-input v-emoji v-model="record.register_address_start" ref="registerStart" class="addTypeForm" size='small'></el-input>
      </el-form-item>
      <el-form-item label-width="0" v-if="showPositionList.includes(record.register_interval)" prop="register_address_start_position">
        {{$t('位')}} <el-select v-model="record.register_address_start_position" ref="startPosition" style="width:70px" size='small'>
          <el-option v-for="val in positionList" :key="val" :label="val" :value="val">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('寄存器结束地址')" prop="register_address_end" style="margin-right:0">
        <el-input ref="registerEnd" v-emoji v-model="record.register_address_end" class="addTypeForm" size='small'></el-input>
      </el-form-item>
      <el-form-item label-width="0" v-if="showPositionList.includes(record.register_interval)" prop="register_address_end_position">
        {{$t('位')}} <el-select v-model="record.register_address_end_position" ref="endPosition" style="width:70px" size='small'>
          <el-option v-for="val in positionList" :key="val" :label="val" :value="val">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('寄存器值类型')" prop="register_value_type" v-if="func === '0x05'">
        <el-select v-model="record.register_value_type" class="addTypeForm" size='small' ref="valueType" filterable @change="valueTypeChange">
          <el-option v-for="(value, key) in valueTypeList" :key="key" :label="$t(value)" :value="key">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('寄存器值范围')" prop="register_value_range_select" key="register_value_range_select" v-if="func === '0x05' && record.register_value_type === '3'" style="margin-right:0">
        <el-select v-model="record.register_value_range_select" ref="rangeSelect" class="addTypeForm" size='small'>
          <el-option v-for="(value, key) in rangeList" :key="key" :label="$t(value)" :value="key">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('寄存器值范围')" prop="register_value_range_start" v-if="record.register_value_type !== '3' && func === '0x05'" key="register_value_range_start" style="margin-right:0">
        <el-input v-emoji v-model="record.register_value_range_start" ref="range" style="width:117px" size='small'></el-input>
      </el-form-item>
      <el-form-item label="" v-if="record.register_value_type !== '3' && func === '0x05'" style="margin-right:0">~</el-form-item>
      <el-form-item label-width="0" v-if="record.register_value_type !== '3' && func === '0x05'" prop="register_value_range_end">
        <el-input v-emoji v-model="record.register_value_range_end" ref='registe' style="width:117px" size='small'></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="innerAddSubmitThree">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="innerAddCloseThree">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import ruleArray from '../../ruleArray'
import { inputClass, selectClass } from '@/utils/input-class.js'
export default {
  name: 'AddConfigDialog',
  props: ['addConfigRows'],
  data () {
    var validateName = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (isNaN(Number(value)) || !this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (Number(value) < 0 || Number(value) > 65535) {
        callback(new Error(this.$t('输入范围0~65535')))
      } else if (this.record.register_address_start && this.record.register_address_end && (Number(this.record.register_address_start) > Number(this.record.register_address_end))) {
        callback(new Error(this.$t('起始地址必须小于结束地址')))
      } else {
        this.chearRule('register_address_start')
        this.chearRule('register_address_end')
        callback()
      }
    }
    var validateDbNum = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (isNaN(Number(value)) || !this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (Number(value) < 0 || Number(value) > 256) {
        callback(new Error(this.$t('输入范围0~256')))
      } else {
        callback()
      }
    }
    var validateValue = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (!this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else {
        switch (this.record.register_value_type) {
          case '0':
            if (Number(value) < 0 || Number(value) > 4294967295) {
              callback(new Error(this.$t('输入范围0~4294967295')))
            }
            break

          case '4':
            if (Number(value) < 0 || Number(value) > 4294967295) {
              callback(new Error(this.$t('输入范围0~4294967295')))
            }
            break
          case '5':
            if (Number(value) < -32768 || Number(value) > 32768) {
              callback(new Error(this.$t('输入范围-32768~32768')))
            }
            break
          case '6':
            if (Number(value) < -2147483648 || Number(value) > 2147483648) {
              callback(new Error(this.$t('输入范围-2147483648~2147483648')))
            }
            break
        }
        if (this.record.register_value_range_start && this.record.register_value_range_end && (Number(this.record.register_value_range_start) > Number(this.record.register_value_range_end))) {
          if (rule.field === 'register_value_range_start') {
            callback(new Error(this.$t('不能大于最大值')))
          } else {
            callback(new Error(this.$t('不能小于最小值')))
          }
        } else {
          this.chearRule('register_value_range_start')
          this.chearRule('register_value_range_end')
        }
        callback()
      }
    }
    return {
      dialogVisible: false,
      key: 1,
      record: {
        db_num: '',
        register_address_end: '',
        register_address_end_position: '0',
        register_address_start: '',
        register_address_start_position: '0',
        register_interval: 'P',
        register_value_range_select: '0',
        register_value_range_end: '',
        register_value_range_start: '',
        register_value_type: '0'
      },
      recordCopy: {
        db_num: '',
        register_address_end: '',
        register_address_end_position: '0',
        register_address_start: '',
        register_address_start_position: '0',
        register_interval: 'P',
        register_value_range_select: '0',
        register_value_range_end: '',
        register_value_range_start: '',
        register_value_type: '0'
      },
      intervalList: ruleArray.intervalList,
      valueTypeList: ruleArray.valueTypeList,
      rangeList: ruleArray.rangeList,
      showPositionList: ['I', 'Q', 'M', 'DB', 'DI'],
      showDbNumList: ['DB', 'DI'],
      positionList: ['0', '1', '2', '3', '4', '5', '6', '7'],
      func: '',
      rules: {
        register_address_start: [{ required: false, validator: validateName, trigger: 'blur' }],
        register_address_end: { required: false, validator: validateName, trigger: 'blur' },
        register_value_range_start: { required: false, validator: validateValue, trigger: 'blur' },
        register_value_range_end: { required: false, validator: validateValue, trigger: 'blur' },
        db_num: { required: false, validator: validateDbNum, trigger: 'blur' }
      }
    }
  },
  computed: {
    change () {
      const register_value_type = this.record.register_value_type
      const func = this.func
      return { register_value_type, func }
    }
  },
  watch: {
    change (val) {
      if (val.func === '0x05') {
        this.$nextTick(() => {
          selectClass(this.$refs, ['valueType'])
        })
        if (val.register_value_type !== '3') {
          this.$nextTick(() => {
            const data = ['range', 'registe']
            inputClass(this.$refs, data)
          })
        }
      }
    },
    'record.register_interval' (val) {
      if (this.showDbNumList.includes(val)) {
        this.key = this.key + 1
        this.$nextTick(() => {
          inputClass(this.$refs, ['num'])
        })
      }
      if (this.showPositionList.includes(val)) {
        this.$nextTick(() => {
          const selectData = ['startPosition', 'endPosition']
          const data = ['registerEnd']
          selectClass(this.$refs, selectData)
          inputClass(this.$refs, data)
        })
      }
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['registerEnd', 'registerStart']
        const selectData = ['interval']
        selectClass(this.$refs, selectData)
        inputClass(this.$refs, data)
      })
      this.func = data
      if (data === '0x05') {
        this.record.register_value_type = '0'
      }
    },
    intervalChange (val) {
      this.record.register_address_end_position = '0'
      this.record.register_address_start_position = '0'
      if (this.showDbNumList.includes(val)) {
        this.record.db_num = '0'
      } else {
        this.record.db_num = ''
      }
      this.$refs.form.clearValidate()
    },
    valueTypeChange (type) {
      this.record.register_value_range_start = ''
      this.record.register_value_range_end = ''
      this.record.register_value_range_select = '0'
      this.$refs.form.clearValidate(['register_value_range_start', 'register_value_range_end'])
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit('addConfigRows', Object.assign({}, this.record))
          this.close()
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.form.resetFields()
    },
    isInteger (value) {
      return (!isNaN(value) && (parseInt(value).toString().length === String(Number(value)).length))
    },
    chearRule (name) {
      if (!isNaN(Number(this.record[name])) && this.isInteger(this.record[name]) && (Number(this.record[name]) >= 0 && Number(this.record[name]) <= 65535)) {
        this.$refs['form'].clearValidate([name])
      }
    }
  }
}
</script>
<style lang="scss">
.addTypeForm {
  width: 250px !important;
}
</style>
